package com.yanftch.hdc_tools.insertcode

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.command.WriteCommandAction
import com.yanftch.hdc_tools.common.MessageDelegate.error
import com.yanftch.hdc_tools.common.mergeLists
import com.yanftch.hdc_tools.insertcode.bean.CodeBean
import com.yanftch.hdc_tools.insertcode.dialog.InsertCodeFrame
import com.yanftch.hdc_tools.insertcode.dialog.InsertCodeFrame.OnSelectListener
import com.yanftch.hdc_tools.insertcode.storage.InsertCodeState.loadJsonFromFile
import com.yanftch.hdc_tools.insertcode.util.FileUtils
import com.yanftch.hdc_tools.insertcode.util.GsonUtils.jsonToList
import java.util.*
import javax.swing.SwingWorker

class InsertCodeAction : AnAction() {
    var mAnActionEvent: AnActionEvent? = null

    override fun actionPerformed(e: AnActionEvent) {
        mAnActionEvent = e

        //        String configPath = PathManager.getConfigPath();
//        System.out.println("日志1：" + configPath);
        try {
            getWorker().execute()
            //            worker.execute();
//            List<CodeBean> defaultList = FileUtils.getList();
//            String loadJsonFromFile = InsertCodeState.INSTANCE.loadJsonFromFile();
//            List<CodeBean> userList = com.alibaba.fastjson.JSONObject.parseArray(loadJsonFromFile, CodeBean.class);
//            List<CodeBean> realList = new ArrayList<>();
//            if (userList != null && !userList.isEmpty()) {
//                realList.addAll(userList);
//            } else {
//                realList.addAll(defaultList);
//            }
//            // 打印解析后的结果
////            for (CodeBean code : realList) {
////                System.out.println("模板列表：name=" + code.getName() + ", value=" + code.getValue());
////            }
//
//            // 显示弹窗
////            CodeDialog codeDialog = new CodeDialog(realList);
////            codeDialog.show();
//            CodeFrame frame = new CodeFrame(realList);
//            frame.setListener(code -> {
////                    System.out.println("选中：name=" + code.getName() + ", value=" + code.getValue());
//                boolean error = code.getValue() == null || code.getValue().isEmpty();
//                insert(e, error ? "" : code.getValue());
//            });
        } catch (exception: Exception) {
            error("出错了，掘金上联系下开发者吧~", e)
        }
    }

    inner class getWorker : SwingWorker<List<CodeBean>, String>() {
        @Throws(Exception::class)
        override fun doInBackground(): List<CodeBean> {
            val result: MutableList<CodeBean> = mutableListOf()
            try {
                // 默认配置数据
                val defaultList = FileUtils.getList()
                val loadJsonFromFile = loadJsonFromFile()
                // 用户配置数据
                val userList = jsonToList(loadJsonFromFile, CodeBean::class.java)
                val mergedLists: List<CodeBean> = mergeLists(userList, defaultList)
                result.addAll(mergedLists)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return result
        }

        override fun done() {
            try {
                val realList = get()
                var sortedBy = realList.sortedBy { it.name.lowercase() }
                val frame = InsertCodeFrame(sortedBy)
                frame.setListener(object : OnSelectListener {
                    override fun onSelect(code: CodeBean) {
                        val error = code.value == null || code.value.isEmpty()
                        insert(mAnActionEvent, if (error) "" else code.value)
                    }
                })
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 插入代码
     */
    fun insert(e: AnActionEvent?, value: String) {
        e?.let {
            // 获取当前的项目和编辑器
            val project = e.project
            val editor = e.getData(CommonDataKeys.EDITOR)

            if (editor != null && project != null) {
                WriteCommandAction.runWriteCommandAction(project) {
                    // 获取 Document 和 CaretModel
                    val document = editor.document
                    val caretModel = editor.caretModel

                    // 获取当前光标位置
                    val offset = caretModel.offset

                    // 插入文本：开始写入操作
                    editor.document.insertString(offset, value)

                    // 可选：移动光标到插入文本的末尾
                    caretModel.moveToOffset(offset + value.length)
                }
            }
        }
    }


}
